import { Carousel, Col, Icon, Row } from "antd";
import { Card, List, ListView, Modal, NoticeBar } from 'antd-mobile';
import Grid from "antd-mobile/lib/grid";
import moment from "moment";
import { addon } from "pao-aop";
import { reactControl, ReactView, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
import { getLocation } from "src/business/models/location";
import { request, setMainFormTitle } from "src/business/util_tool";
import { CarouselData } from "src/models/carousel";
import { AppServiceUtility } from "src/projects/app/appService";
import { ROUTE_PATH } from "src/projects/app/util-tool";
import { FontIcon } from "src/projects/components/icon";
import './index.less';
import { LoadingEffectView } from "src/business/views/loading-effect";
const Item = List.Item;
function MyBody(props: any) {
    return (
        <div className="am-list-body my-body" style={{ height: '100%' }}>
            {props.children}
        </div>
    );
}

/**
 * 组件：首页视图控件状态
 */
export interface HomeViewState extends ReactViewState {
    /** 轮播数据 */
    data?: CarouselData[];
    /** 图标数据 */
    icon_data?: any[];
    /** 请求的数据 */
    list?: any[];
    /** 长列表数据 */
    dataSource?: any;
    /** 长列表容器高度 */
    height?: any;
    // 冠名基金数据
    title_fund_data?: any;
    // 模态窗
    noticeModal: boolean;
    // 最新记录数据
    new_record?: any;
    upload?: boolean;
    upload_new?: boolean;
    upload_charitable?: boolean;
}
// 去除HTML Tag，空格，nbsp，换行符
export function filterHTMLTag(msg: string) {
    if (msg && msg.length > 0) {
        return msg.replace(/<\/?[^>]*>/g, '').replace(/[|]*\n/, '').replace(/&nbsp;/ig, '').replace(/[\r\n]/g, '');
    }
    return msg;
}
/**
 * 组件：首页视图控件
 */
export class HomeView extends ReactView<HomeViewControl, HomeViewState> {
    constructor(props: any) {
        super(props);
        const ds = new ListView.DataSource({
            rowHasChanged: (r1: any, r2: any) => r1 !== r2
        });
        this.state = {
            dataSource: ds,
            title_fund_data: [],
            list: [],
            noticeModal: false,
            height: document.documentElement!.clientHeight,
            new_record: [],
            icon_data: [{ text: '机构养老', icon: <FontIcon style={{ fontSize: '40px' }} type="iconziyuan39" /> },
            { text: '社区服务中心', icon: <FontIcon style={{ fontSize: '40px' }} type="iconziyuan35" /> },
            { text: '居家服务', icon: <FontIcon style={{ fontSize: '40px' }} type="iconziyuan28" /> },
            { text: '政策类申请', icon: <FontIcon style={{ fontSize: '40px' }} type="iconziyuan38" /> },
            // { text: '平安出行', icon: <FontIcon style={{ fontSize: '40px' }} type="iconziyuan17" /> },
            { text: '慈善基金', icon: <FontIcon style={{ fontSize: '40px' }} type="iconziyuan37" /> },
            { text: '服务需求', icon: <FontIcon style={{ fontSize: '40px' }} type="iconziyuan1" /> },
                // { text: '356健康服务', icon: <FontIcon style={{ fontSize: '40px' }} type="iconziyuan1" /> },
                // { text: '更多', icon: <FontIcon style={{ fontSize: '40px' }} type="iconziyuan11" /> },
                // { text: '医疗绿色通道', icon: <Icon style={{ fontSize: '40px' }} type="book" /> },
                // { text: '国家政策发布', icon: <Icon style={{ fontSize: '40px' }} type="book" /> },
                // { text: '法律心理咨询', icon: <Icon style={{ fontSize: '40px' }} type="book" /> },
                // { text: '慈善捐赠列表', icon: <Icon style={{ fontSize: '40px' }} type="book" /> },
                // { text: '慈善项目列表', icon: <Icon style={{ fontSize: '40px' }} type="book" /> },
                // { text: '申请募捐', icon: <Icon style={{ fontSize: '40px' }} type="book" /> },
                // { text: '申请募捐列表', icon: <Icon style={{ fontSize: '40px' }} type="book" /> },
            ],
            upload: true,
            upload_new: true,
            upload_charitable: true,
        };
    }
    componentDidMount() {
        request(this, AppServiceUtility.article_list_service.get_news_list_picture!({}))
            .then((data: any) => {
                if (data.result.length > 0) {
                    let picture_list = data.result.map((key: any, value: any) => {
                        let picture: CarouselData = { id: '', name: '', urls: '' };
                        picture['id'] = key['title'];
                        picture['name'] = key['title'];
                        picture['urls'] = key['picture'];
                        return picture;
                    });
                    this.setState({
                        data: picture_list,
                    });
                }
            });

        // 修改统一新闻接口
        AppServiceUtility.article_list_service.get_news_list!({}, 1, 10)!
            .then((data: any) => {
                this.setState({ upload_new: false });
                if (data.result) {
                    this.setState({
                        list: data.result
                    });
                }
            })
            .catch((err) => {
                this.setState({ upload_new: false });
                console.info(err);
            });
        AppServiceUtility.personnel_service.get_user_session!()!
            .then((data: any) => {
                if (data) {
                    // 最近记录
                    AppServiceUtility.operation_record.get_record_list!({}, 1, 5)!
                        .then((data: any) => {
                            this.setState({ upload: false });
                            if (data.result) {
                                this.setState({
                                    new_record: data.result,
                                });
                            }
                        })
                        .catch((err) => {
                            this.setState({ upload: false });
                            console.info(err);
                        });
                }
            });

        // 获取冠名基金
        request(this, AppServiceUtility.charitable_service.get_charitable_title_fund_list!({ 'audit_status': '通过', 'donate_type': '基金' }, 1, 10))
            .then((data: any) => {
                this.setState({ upload_charitable: false });
                if (data.result.length > 0) {
                    this.setState({
                        title_fund_data: data.result,
                    });
                }
            })
            .catch((err) => {
                this.setState({ upload_charitable: false });
                console.info(err);
            });
    }
    onClickRow = (id: string) => {
        console.info(id);
        this.props.history!.push(ROUTE_PATH.newsInfo + '/' + id);
    }
    grid_click = (_el: any) => {
        switch (_el.text) {
            case '机构养老':
                this.props.history!.push(ROUTE_PATH.beadhouseList);
                break;
            case '活动列表':
                this.props.history!.push(ROUTE_PATH.activityList);
                break;
            case '活动室列表':
                this.props.history!.push(ROUTE_PATH.activityRoomList);
                break;
            case '养老补助申请':
                this.props.history!.push(ROUTE_PATH.applicationSubsidies);
                break;
            case '服务列表':
                this.props.history!.push(ROUTE_PATH.serviceList);
                break;
            case '新闻列表':
                this.props.history!.push(ROUTE_PATH.newsList);
                break;
            case '我的订单':
                this.props.history!.push(ROUTE_PATH.myOrder);
                break;
            case '居家服务':
                this.props.history!.push(ROUTE_PATH.homeCare);
                break;
            case '慈善基金':
                this.props.history!.push(ROUTE_PATH.charitableTitleFundList);
                break;
            case '社区服务中心':
                this.props.history!.push(ROUTE_PATH.communityList);
                break;
            case '消息管理':
                this.props.history!.push(ROUTE_PATH.messageList);
                break;
            case '幸福小站':
                this.props.history!.push(ROUTE_PATH.servicePackageList + '/xfxz');
                break;
            case '政策类申请':
                this.props.history!.push(ROUTE_PATH.pensionBenefitsNav);
                break;
            case '服务需求':
                this.props.history!.push(ROUTE_PATH.serviceDemand);
                break;
            case '更多':
                this.getMore();
                break;
            default:
                break;
        }
    }
    title_click = () => {
        this.props.history!.push(ROUTE_PATH.newsList);
    }

    getMore = () => {
        let icon_data: any = this.state.icon_data;
        icon_data.map((item: any, index: any) => {
            if (item.text === '更多') {
                icon_data.splice(index, 1);
            }
        });
        let list = [
            { text: '医疗绿色通道', icon: <Icon style={{ fontSize: '40px' }} type="book" theme="twoTone" /> },
            { text: '国家政策发布', icon: <Icon style={{ fontSize: '40px' }} type="book" theme="twoTone" /> },
            { text: '法律心理咨询', icon: <Icon style={{ fontSize: '40px' }} type="book" theme="twoTone" /> },
            { text: '消息管理', icon: <Icon style={{ fontSize: '40px' }} type="book" theme="twoTone" /> },
        ];
        let newlist = [...icon_data, ...list];
        this.setState({
            icon_data: newlist
        });
    }
    showNoticeModal() {
        this.setState({
            noticeModal: true,
        });
    }
    closeNoticeModal() {
        this.setState({
            noticeModal: false,
        });
    }
    location = (position: any) => {
        // alert(position.coords.longitude);
    }
    new_recode_click = (id: any) => {
        let str = id.split('/');
        switch (str[1]) {
            case '订单':
                this.props.history!.push(ROUTE_PATH.orderDetail + '/' + str[0]);
                break;
            case '报名活动':
                this.props.history!.push(ROUTE_PATH.activityDetail + '/' + str[0]);
                break;
            case '关注机构':
                this.props.history!.push(ROUTE_PATH.beadhouseInfo + '/' + str[0]);
                break;
            case '发布活动':
                this.props.history!.push(ROUTE_PATH.activityDetail + '/' + str[0]);
                break;
            case '待审核活动':
                this.props.history!.push(ROUTE_PATH.activityDetail + '/' + str[0]);
                break;
            case '活动签到':
                this.props.history!.push(ROUTE_PATH.activityDetail + '/' + str[0]);
                break;
            default:
                break;
        }
    }
    render() {
        setMainFormTitle('南海区智慧康养');
        const MyHeader = () => {
            return (
                <div className="my-header">
                    {this.props.children}
                    <span style={{ fontWeight: "bolder", fontSize: "x-large", color: "black" }}>新鲜事</span>
                    <a onClick={this.title_click} style={{ float: "right", fontSize: "small", color: "gray" }}>查看更多></a>
                </div>
            );
        };
        const { list, dataSource, } = this.state;
        const renderRow = (owData: any, sectionID: any, rowID: any) => {
            return (
                <Card className='list-conten'>
                    <Row type='flex' justify='center' onClick={this.onClickRow.bind(this, owData.id)}>
                        <Col className='list-col' span={10}><img src={owData.app_img_list && owData.app_img_list[0] ? owData.app_img_list[0] : ''} style={{ height: '72pt', width: '110pt' }} /></Col>
                        <Col span={14} className='list-col'>
                            <Row
                                className="maxLine2"
                                style={{ WebkitBoxOrient: 'vertical' }}
                            >
                                <strong>{owData.title}</strong>
                            </Row>
                            <Row
                                className="maxLine2"
                                style={{ WebkitBoxOrient: 'vertical' }}
                            >
                                {filterHTMLTag(owData.content)}
                            </Row>
                            <Row>
                                <span style={{ float: 'left', textAlign: 'left' }}>
                                    {moment(owData.create_date).format("MM-DD hh:mm")}
                                </span>
                                <span style={{ float: 'right', textAlign: 'right' }}>
                                    <span style={{ marginRight: '10px' }}>
                                        <Icon type="like" style={{ marginRight: '5px' }} />{owData.likes || 0}
                                    </span>
                                    <span style={{ marginRight: '10px' }}>
                                        <Icon type="chrome" style={{ marginRight: '5px' }} />{owData.share || 0}
                                    </span>
                                </span>
                            </Row>
                        </Col>
                    </Row>
                </Card>
            );
        };
        // let dom1 = (
        //     <a
        //         className='carousel-a'
        //         href="javascript:;"
        //     >
        //         <img
        //             className='carousel-img'
        //             src='https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3127374192,2181440598&fm=26&gp=0.jpg'
        //             alt=""
        //             onLoad={() => {
        //                 window.dispatchEvent(new Event('resize'));
        //             }}
        //         />
        //     </a>);
        const title_fund_data = this.state.title_fund_data;
        getLocation(this.location);
        return (
            <div>
                <Carousel
                    autoplay={true}
                    infinite={true}
                    autoplaySpeed={5000}
                // beforeChange={(from, to) => console.log(`slide from ${from} to ${to}`)}
                // afterChange={index => console.log('slide to', index)}
                >
                    {this.state.data ? this.state.data!.map((val: CarouselData, index: number) => (
                        <a
                            className='carousel-a'
                            key={index}
                            href="javascript:;"
                        >
                            <img
                                className='carousel-img'
                                src={val.urls}
                                alt=""
                                onLoad={() => {
                                    window.dispatchEvent(new Event('resize'));
                                }}
                            />
                            <div style={{ background: 'rgba(0,0,0,0.1)', position: 'absolute', bottom: '0', width: '100%', color: '#fff', paddingLeft: '10px' }}><div style={{ background: 'none', wordBreak: 'break-all', textOverflow: 'ellipsis', overflow: 'hidden', display: ' -webkit-box', WebkitLineClamp: 1, WebkitBoxOrient: 'vertical', }}>{val.name}</div></div>
                        </a>
                    )) : null}
                </Carousel>
                <Grid data={this.state.icon_data} activeStyle={true} columnNum={3} onClick={_el => this.grid_click(_el)} />
                {
                    this.state.new_record && this.state.new_record.length > 0 ?
                        <List renderHeader={() => '最近记录'} style={{ marginBottom: '15px' }}>
                            {this.state.upload && <LoadingEffectView />}
                            {
                                this.state.new_record.map((value: any) => {
                                    return (
                                        <Item onClick={this.new_recode_click.bind(this, value.business_id + '/' + value.type)} key={value.id}>最新{value.type}：{value.content}</Item>
                                    );
                                })
                            }
                        </List>
                        :
                        ''
                }
                <NoticeBar mode="link" onClick={() => { this.showNoticeModal(); }} marqueeProps={{ loop: true, style: { padding: '0 7.5px' } }}>
                    {(() => {
                        if (title_fund_data.length > 0) {
                            return title_fund_data.map((item: any, index: number) => {
                                return `感谢${item.donate_name}捐助基金金额：${item.donate_money}  `;
                            });
                        }
                        return '';
                    })()}
                </NoticeBar>
                <Modal
                    visible={this.state.noticeModal}
                    transparent={true}
                    maskClosable={true}
                    title="基金信息"
                    footer={[{ text: 'Ok', onPress: () => { console.log('ok'); this.closeNoticeModal(); } }]}
                >
                    {this.state.upload_charitable && <LoadingEffectView />}
                    <div style={{ height: 100, overflow: 'scroll' }}>
                        {(() => {
                            if (title_fund_data.length > 0) {
                                return title_fund_data.map((item: any, index: number) => {
                                    return (
                                        <p key={index}>{item.donate_name}捐助基金金额：${item.donate_money}</p>
                                    );
                                });
                            }
                            return '';
                        })()}
                    </div>
                </Modal>
                <Row>
                    <div className='top-list-view'>
                        {this.state.upload_new && <LoadingEffectView />}
                        {
                            list && list.length ?
                                <ListView
                                    ref={el => this['lv'] = el}
                                    dataSource={dataSource.cloneWithRows(list)}
                                    renderRow={renderRow}
                                    initialListSize={10}
                                    pageSize={10}
                                    renderHeader={MyHeader}
                                    renderBodyComponent={() => <MyBody />}
                                    style={{
                                        height: this.state.height,
                                    }}
                                /> : null
                        }
                    </div>
                </Row>

            </div >
        );
    }
}

/**
 * 组件：首页视图控件
 * 控制首页视图控件
 */
@addon('HomeView', '首页视图控件', '控制首页视图控件')
@reactControl(HomeView, true)
export class HomeViewControl extends ReactViewControl {
    constructor() {
        super();
    }
}